﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static LoanOperations.LoanOperations;
using static AccountOperations.AccountOperations;
using System.DirectoryServices.ActiveDirectory;
using System.Net;

namespace Bank_database_system.业务部.贷款业务
{
    public partial class 贷款查询d : UserControl
    {
        private string loanState = "";
        public event EventHandler ButtonBack;
        private string branch_id = "";
        private string staff_id = "";
        public 贷款查询d()
        {
            InitializeComponent();
        }

        public void branch_and_staff_get(string branchID, string staffID)
        {
            branch_id = branchID;
            staff_id = staffID;
        }

        public void Loan_Set(string cardID, string loanID)
        {
            textBox5.Text = cardID;
            //其它
            DataTable loanTable = GetLoansByLoanID(loanID);
            DataTable customerTable = CustomerInquiryByCardID(cardID);
            if (loanTable != null && loanTable.Rows.Count > 0
                && customerTable != null && customerTable.Rows.Count > 0)
            {
                DataRow row = loanTable.Rows[0];
                string amount = row["AMOUNT"].ToString();
                string repayment = row["REPAYMENT_BALANCE"].ToString();
                string rate = row["INTEREST_RATE"].ToString();
                DateTime dateTime1 = Convert.ToDateTime(row["BEGIN_TIME"]);
                DateTime dateTime2 = Convert.ToDateTime(row["END_TIME"]);
                loanState = row["STATE"].ToString();
                // 计算时间差
                int yearDifference = dateTime2.Year - dateTime1.Year;

                row = customerTable.Rows[0];
                string name = row["NAME"].ToString();
                string ID = row["IDENTIFICATION_NUMBER"].ToString();
                string phone = row["PHONENUMBER"].ToString();
                string address = row["ADDRESS"].ToString();

                textBox1.Text = loanID;
                textBox2.Text = name;
                textBox4.Text = ID;
                textBox3.Text = phone;
                textBox9.Text = address;
                textBox8.Text = amount;
                textBox7.Text = repayment;
                textBox6.Text = rate;
                textBox13.Text = dateTime1.ToString();
                textBox12.Text = dateTime2.ToString();
                textBox11.Text = yearDifference + " 年";
                textBox10.Text = cardID;
            }
            else
            {
                MessageBox.Show("查询失败，请稍后再试！");
                button1_Click(this, EventArgs.Empty);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
            textBox7.Text = "";
            textBox8.Text = "";
            textBox9.Text = "";
            textBox10.Text = "";
            textBox11.Text = "";
            textBox12.Text = "";
            textBox13.Text = "";
            ButtonBack?.Invoke(this, EventArgs.Empty);
        }

        private decimal CheckCardBalance()
        {
            string cardID = textBox5.Text;
            string balance = BankCardBalanceInquiry(cardID);
            decimal num1 = decimal.Parse(balance);
            decimal num2 = decimal.Parse(textBox7.Text);
            if (num1 - num2 < 0)
            {
                MessageBox.Show("银行卡余额不足，无法提前还款！");
            }
            return num1 - num2;
        }

        private bool CheckCardState()
        {
            string cardID = textBox5.Text;
            if (BankCardStateInquiry(cardID) == "冻结")
            {
                MessageBox.Show("银行卡状态为冻结，不可提前还款！");
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool CheckLoanState()
        {
            if (loanState == "还款中")
            {
                return true;
            }
            else
            {
                MessageBox.Show("贷款已结束，无需提前还款！");
                return false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!CheckLoanState())
            {
                return;
            }

            DialogResult result = MessageBox.Show("请再次确认是否提前还款！", "确认保存", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                decimal newBalance = CheckCardBalance();
                if (CheckCardState() && newBalance > 0)
                {
                    string repayment = textBox7.Text;
                    //提前还款
                    string hostName = Dns.GetHostName(); // 获取主机名
                    string cardID = textBox5.Text;
                    IPAddress[] ipAddresses = Dns.GetHostAddresses(hostName); // 获取本机的IP地址
                    IPAddress ipv4 = ipAddresses.FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                    if (ipv4 == null)
                    {
                        MessageBox.Show("获取IP地址出现错误，请检查网络后重试！");
                        return;
                    }
                    string ip = ipv4.ToString();
                    string branchCard = GetLoanBackCard(textBox1.Text);
                    decimal repaymentValue = Decimal.Parse(repayment);

                    string retult = Transfer.TransferBusiness(cardID, branchCard, ip, repaymentValue, staff_id);
                    DeleteRepayment(textBox1.Text);
                    LoanToEnd(textBox1.Text);
                    textBox7.Text = "0";
                    string message = "提前还款，贷款ID为" + textBox1.Text;
                    OperateRecordHandler.InsertOperateRecord(staff_id, "提前还款", message, textBox1.Text, "", "", "");
                    int amount = (int)(GetLoanAmount(textBox1.Text) / 10);
                    UpdateCreditScore(textBox5.Text, amount);

                    MessageBox.Show("提前还款成功！");
                    ButtonBack?.Invoke(this, EventArgs.Empty);
                    //前端显示调用需改变的部分
                }
            }
        }
    }
}
